package com.scores.controller;


import com.scores.pojo.Teacher;
import com.scores.service.TeacherService;
import com.scores.utils.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/teacher")
public class TeacherController  {

    @Autowired
    TeacherService teacherService;

    @RequestMapping("/teacherLogin")
    public Results<String> login(String userName, String password, String userCode, HttpSession session) {
        if (CodeController.isEquals(userCode, session)) {
            Teacher teacher = new Teacher(userName, password);
            List<Teacher> result = teacherService.getAllTeachers(teacher);
            if (!result.isEmpty()) {
                Teacher loggedInTeacher = result.get(0);
                session.setAttribute("loginUser", loggedInTeacher);
                return new Results<>("0", "登录成功");
            } else {
                return new Results<>("2", "用户名或密码错误");
            }
        } else {
            return new Results<>("1", "验证码错误");
        }
    }



    @RequestMapping("/getAllTeachers")
    public List<Teacher> getAllTeachers() {
        return teacherService.getAllTeachers(new Teacher());
    }

    @RequestMapping("/updatePassword")
    public Results<String> updatePassword(String oldPassword, String newPassword, HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("loginUser");
        String realPassword = teacher.getTeacherPass();
        if(!Objects.equals(realPassword, oldPassword)) {
            return new Results<>("1", "旧密码错误", null, 0);
        }
        if(Objects.equals(oldPassword, newPassword)) {
            return new Results<>("1", "新密码不能与旧密码相同", null, 0);
        }

        int resultCode = teacherService.updatePassword(teacher.getId(), newPassword);
        if (resultCode == 0) {
            session.invalidate();
            return new Results<>("0", "密码更新成功，请重新登录", null, 0);
        } else {
            return new Results<>("2", "密码更新失败", null, 0);
        }

    }

}
